package algo;

/**
 * @author Ajie
 * @date 8/6/24
 * @function
 */
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;
import java.awt.*;

public class BarChartExample extends JFrame {

    public BarChartExample(String title) {
        super(title);

        // 创建数据集
        DefaultCategoryDataset dataset = createDataset();

        // 创建图表
        JFreeChart barChart = ChartFactory.createBarChart(
                "Programming Languages Usage",
                "Language",
                "Percentage",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);

        // 将图表放入面板中
        ChartPanel chartPanel = new ChartPanel(barChart);
        chartPanel.setPreferredSize(new Dimension(800, 600));
        setContentPane(chartPanel);
    }

    private DefaultCategoryDataset createDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        dataset.addValue(40, "Usage", "Java");
        dataset.addValue(30, "Usage", "Python");
        dataset.addValue(20, "Usage", "C++");
        dataset.addValue(10, "Usage", "C#");

        return dataset;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            BarChartExample example = new BarChartExample("Bar Chart Example");
            example.setSize(800, 600);
            example.setLocationRelativeTo(null);
            example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            example.setVisible(true);
        });
    }
}